﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace klipboardtranslator
{
    public partial class MainForm : Form
    {
        private Translator trObject;
        private const int MYKEYID = 0;
        private const int WM_HOTKEY = 0x312;
        private const int MOD_ALT = 1;
        private const int MOD_CONTROL = 2;
        private const int MOD_SHIFT = 4;
        [DllImport("user32.dll")]
        private static extern int RegisterHotKey(IntPtr hWnd, int id, int modifier, Keys vk);
        [DllImport("user32.dll")]
        private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);



        public MainForm()
        {
            InitializeComponent();
            trObject = new Translator("auto|en");
            tbxMain.Text = "Usage: select and copy the text you want to translate (CTRL + C), then press CTRL + SHIFT + C for it to appear translated in this box.";
            tbxMain.Text += Environment.NewLine + "Google Translate is used for performing the translation.";

            RegisterHotKey(this.Handle, MYKEYID, MOD_CONTROL + MOD_SHIFT, Keys.C);
            this.FormClosing += Form1_FormClosing;
        }

        private void OnShortcutAction()
        {
            string strNewText;
            //translate on the shortcut activation:
            //check if we have text
            if (Clipboard.ContainsText())
            {
                strNewText = trObject.TranslateText(Clipboard.GetText());
            }
            else
            {
                strNewText = "No text copied in Clipboard\n";
            }

            tbxMain.Text = strNewText + Environment.NewLine + Environment.NewLine + tbxMain.Text;

        }

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_HOTKEY && m.WParam.ToInt32() == MYKEYID)
            {
                this.Visible = true;
                if (this.WindowState == FormWindowState.Minimized)
                    this.WindowState = FormWindowState.Normal;

                OnShortcutAction();

                SetForegroundWindow(this.Handle);
            }
            base.WndProc(ref m);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            UnregisterHotKey(this.Handle, MYKEYID);
        }

    }
}
